import store from '@/store/index.js'
import httpApi from '@/network/api/index.js'

// 单个文件上传
export const uploadFile = (filePath) => {
	let {
		token
	} = store.getters
	return new Promise((resolve) => {
		uni.uploadFile({
			url: httpApi.api.file_upload_path,
			filePath,
			name: 'file',
			header: {
				token,
				// "Content-Type": 'multipart/form-data'
			},
			success: res => {
				if (res.statusCode !== 200) {
					resolve('')
					return
				}
				let response = JSON.parse(res.data)
				if (response.code != 1 && response.msg) {
					uni.showToast({
						title: response.msg,
						icon: 'none'
					})
				} else if (!response.data) {
					uni.showToast({
						title: `文件上传失败，状态码${response.code}`,
						icon: 'none'
					})
				}
				let netUrlPath = response.data
				resolve(netUrlPath)
			},
			fail: err => {
				console.log('文件上传失败：', err, url, filePath)
				uni.showModal({
					content: err.errMsg,
					showCancel: false
				});
				resolve('')
			}
		});
	})
}

// 多个文件上传
export const uploadFileList = (pathList = []) => {
	return new Promise((resolve) => {
		Promise.all((pathList || []).map(v => uploadFile(v))).then(respList => resolve(respList.filter(v => v)))
	})
}


// 选择图片，上传图片,数量为
export const chooseImageUpload = (number = 1) => {
	return new Promise((resolve, ) => {
		uni.chooseImage({
			count: number,
			// sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: res => {
				let tempFilePaths = res.tempFilePaths;
				uploadFileList(tempFilePaths).then(resolve)
			},
		});
	})
}

export default {
	uploadFile,
	uploadFileList,
	chooseImageUpload,
}